package com.gofunbuy.app.member;

import java.io.IOException;
import java.util.HashMap;

import org.json.JSONException;

import com.gofunbuy.R;
import com.gofunbuy.TabMemberGroup;
import com.gofunbuy.app.home.HomeActivity;
import com.gofunbuy.http.HttpClientImpl;
import com.gofunbuy.util.GoFunBuyUtils;
import com.gofunbuy.util.GoFunBuyUtils.GoFunBuyInterface;
import com.gofunbuy.util.GoFunBuyUtils.GoFunBuyInterface.ProtocalStatics;
import com.gofunbuy.util.GoFunBuyUtils.RegistXML;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class SubMemberRegistActivity extends Activity implements
		OnClickListener, GoFunBuyInterface {
	private TextView tvBack, tvTitle;
	private Context mContext;
	private EditText etName, etEmail, etPwd, etTel, tePreTel;
	private LinearLayout linearLayoutRegist;
	private String mName, mEmail, mPwd, mTel, mPreTel;
	private RegistXML mRegist;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.member_regist_layout);
		mContext = this;
		initLayout();
	}

	private void initLayout() {
		tvTitle = (TextView) findViewById(R.id.topbar_title);
		tvTitle.setText(R.string.title_regist);
		tvBack = (TextView) findViewById(R.id.topbar_back);
		tvBack.setOnClickListener(this);
		linearLayoutRegist = (LinearLayout) findViewById(R.id.id_member_regist);
		linearLayoutRegist.setOnClickListener(this);
		etName = (EditText) findViewById(R.id.id_regist_name);
		etEmail = (EditText) findViewById(R.id.id_regist_email);
		etPwd = (EditText) findViewById(R.id.id_regist_pwd);
		etTel = (EditText) findViewById(R.id.id_regist_phone);
		tePreTel = (EditText) findViewById(R.id.id_regist_phone_pre);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.topbar_back:
			if (TabMemberGroup.group != null)
				startActivity(TabMemberActivity.class);
			else {
				Intent it = new Intent(this, SubMemberLoginActivity.class);
				startActivity(it);
			}
			break;
		case R.id.id_member_regist:
			if (validateNotEmpty()) {
				if (!GoFunBuyUtils.isNetworkConnected(mContext)) {
					mHandler.sendEmptyMessage(MSG_NETWORD_ERROR);
					return;
				}
				showProgressDialog();
				new Thread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						HashMap<String, String> params = new HashMap<String, String>();

						try {
							params.put(ProtocalStatics.SHOPCODE, "goinside");
							params.put(ProtocalStatics.NAME, mName);
							params.put(ProtocalStatics.EMAIL, mEmail);
							params.put(ProtocalStatics.PWD, mPwd);
							params.put(ProtocalStatics.TEL_CODE, mPreTel);
							params.put(ProtocalStatics.TEL, mTel);

							mRegist = HttpClientImpl.getInstance(mContext)
									.RegistService(mHandler, params);
							if (mRegist != null && mRegist.code != null) {
								if (mRegist.code.equals("1")) {// 註冊成功
									GoFunBuyUtils.writeUsernameToFile(mContext,
											mEmail, mPwd);
									mHandler.sendMessage(mHandler
											.obtainMessage(MSG_REGIST_STATE, 1,
													0));

								} else if (mRegist.code.equals("2")) {// 邮箱已被注册
									mHandler.sendMessage(mHandler
											.obtainMessage(MSG_REGIST_STATE, 2,
													0));
								} else {// 其他错误
									mHandler.sendMessage(mHandler
											.obtainMessage(MSG_REGIST_STATE, 3,
													0));
								}
							} else {
								mHandler.sendMessage(mHandler.obtainMessage(
										MSG_REGIST_STATE, -1, 0));
							}
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}).start();

			}
			break;
		}
	}

	private void startActivity(Class<?> a) {
		// 要跳转的Activity
		// Log.v("名字", a.getSimpleName() + " " + a.getName());
		Intent intent = new Intent(SubMemberRegistActivity.this, a);
		// 把Activity转换成一个Window，然后转换成View
		Window w = TabMemberGroup.group.getLocalActivityManager()
				.startActivity(a.getSimpleName(), intent);
		View view = w.getDecorView();
		// 设置要跳转的Activity显示为本ActivityGroup的内容
		TabMemberGroup.group.setContentView(view);
	}

	private boolean validateNotEmpty() {
		mEmail = etEmail.getText().toString();
		mPwd = etPwd.getText().toString();
		mName = etName.getText().toString();
		mTel = etTel.getText().toString();
		mPreTel = tePreTel.getText().toString();
		if ((mEmail != null && !mEmail.equals(""))
				&& (mPwd != null && !mPwd.equals(""))
				&& (mTel != null && !mTel.equals(""))
				&& (mPreTel != null && !mPreTel.equals(""))
				&& (mName != null && !mName.equals(""))) {
			return true;
		} else {
			Toast.makeText(mContext, R.string.regist_input_error,
					Toast.LENGTH_SHORT).show();
			return false;
		}

	}

	Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case MSG_NETWORD_ERROR:
				hideProgressDialog();
				Toast.makeText(mContext, R.string.network_error,
						Toast.LENGTH_SHORT).show();
				break;
			case MSG_REGIST_STATE:
				hideProgressDialog();
				if (msg.arg1 == 2)
					Toast.makeText(mContext, R.string.regist_email_registed,
							Toast.LENGTH_SHORT).show();
				else if (msg.arg1 == 1) {
					Intent it = new Intent(SubMemberRegistActivity.this,
							HomeActivity.class);
					startActivity(it);
				} else {
					Toast.makeText(mContext, "註冊失敗",
							Toast.LENGTH_SHORT).show();
				}
				break;
			}
		}

	};
	private Dialog mpDialog;

	private void showProgressDialog() {
		View diaView = View
				.inflate(this, R.layout.progress_dialog_layout, null);

		TextView remind = ((TextView) diaView
				.findViewById(R.id.id_progress_dialog_text));
		remind.setText(R.string.registing);
		remind.setTextColor(Color.RED);
		mpDialog = new Dialog(SubMemberRegistActivity.this,
				R.style.processDialog);
		mpDialog.setContentView(diaView);
		mpDialog.show();
	}

	private void hideProgressDialog() {
		if (mpDialog != null && mpDialog.isShowing())
			mpDialog.cancel();
	}
}
